// 获取DOM元素
const audioList = document.getElementById('audio-list');
const refreshBtn = document.getElementById('refresh-audio');
const playBtn = document.getElementById('play-btn');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const audioPlayer = document.getElementById('audio-player');
const audioSource = document.getElementById('audio-source');
const progress = document.getElementById('progress');
const currentTimeEl = document.getElementById('current-time');
const durationEl = document.getElementById('duration');
const nowPlayingImg = document.getElementById('now-playing-img');
const nowPlayingTitle = document.getElementById('now-playing-title');
const nowPlayingArtist = document.getElementById('now-playing-artist');
const progressBar = document.querySelector('.progress-bar');
const ezdax = document.querySelector('#ezdax')
const bat = document.querySelector('#bat')

const Input = document.querySelector('#Input')
const sub = document.querySelector('#bud_')

// 状态变量
let currentTrackIndex = -1;
let tracks = [];
let isPlaying = false;
let isDragging = false;


// 事件监听
refreshBtn.addEventListener('click', handleRefresh);
playBtn.addEventListener('click', togglePlay);
prevBtn.addEventListener('click', prevTrack);
nextBtn.addEventListener('click', nextTrack);
progressBar.addEventListener('click', setProgress);
progressBar.addEventListener('mousedown', () => { isDragging = true; });
document.addEventListener('mousemove', handleProgressDrag);
document.addEventListener('mouseup', handleProgressDragEnd);
audioPlayer.addEventListener('timeupdate', updateProgress);
audioPlayer.addEventListener('ended', nextTrack);
audioPlayer.addEventListener('play', () => {
  isPlaying = true;
  updatePlayButton();
});
audioPlayer.addEventListener('pause', () => {
  isPlaying = false;
  updatePlayButton();
});

// 函数定义
function loadAudioUrls() {
  chrome.storage.local.get(['douyinAudioUrls'], function(result) {  
    tracks = result.douyinAudioUrls || [] ;  
    renderAudioList(tracks);
  }); 
}

function renderAudioList(data) {
  audioList.innerHTML = '';
  
  if (data.length === 0) {
    audioList.innerHTML = `
      <div class="no-music">
        <div class="no-music-icon"><i class="fas fa-music"></i></div>
        <p>没有找到音乐资源</p>
        <p>请刷新页面后点击"刷新列表"</p>
      </div>
    `;
    return;
  }
  
  data.forEach((item, index) => {
    const {url, name, img, adam} = item;
    
    const card = document.createElement('div');
    card.className = 'audio-card';
    if (index === currentTrackIndex) card.classList.add('active');
    
    card.innerHTML = `
      <div class="audio-info">
        <img src="${img}" alt="${name}">
        <div>
          <div class="audio-title">${name}</div>
          <div class="audio-artist">${adam}</div>
        </div>
      </div>
      <div class="audio-actions">
        <button class="action-btn play-btn" data-index="${index}">
          <i class="fas fa-play"></i>
        </button>
        <button class="action-btn download-btn" data-url="${url}" data-name="${name}">
          <i class="fas fa-download"></i>
        </button>
      </div>
    `;
    
    // 更新播放器显示
    nowPlayingImg.src = img;
    nowPlayingTitle.textContent = name;
    nowPlayingArtist.textContent = adam;

    card.addEventListener('click', () => playTrack(index));
    audioList.appendChild(card);
  });
  
  // 添加按钮事件监听
  document.querySelectorAll('.play-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      playTrack(parseInt(btn.dataset.index));
    });
  });
  
  document.querySelectorAll('.download-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      downloadAudio(btn.dataset.url, btn.dataset.name);
    });
  });
}

function playTrack(index) {
  if (index < 0 || index >= tracks.length) return;
  
  currentTrackIndex = index;
  const track = tracks[index];
  
  // 更新播放器显示
  nowPlayingImg.src = track.img;
  nowPlayingTitle.textContent = track.name;
  nowPlayingArtist.textContent = track.adam;
  
  // 设置音频源并播放
  audioSource.src = track.url;
  audioPlayer.load();
  audioPlayer.play()
    .then(() => {
      isPlaying = true;
      updatePlayButton();
      highlightCurrentTrack();
    })
    .catch(e => {
      console.error('播放失败:', e);
      alert('无法播放音频，请尝试下载后播放');
    });
}

function updatePlayButton() {
  playBtn.innerHTML = isPlaying 
    ? '<i class="fas fa-pause"></i>' 
    : '<i class="fas fa-play"></i>';
}

function highlightCurrentTrack() {
  document.querySelectorAll('.audio-card').forEach((card, index) => {
    card.classList.toggle('active', index === currentTrackIndex);
  });
}

function togglePlay() {
  if (currentTrackIndex === -1 && tracks.length > 0) {
    playTrack(0);
    return;
  }
  
  if (isPlaying) {
    audioPlayer.pause();
  } else {
    audioPlayer.play();
  }
  isPlaying = !isPlaying;
  updatePlayButton();
}

function prevTrack() {
  if (tracks.length === 0) return;
  
  let newIndex = currentTrackIndex - 1;
  if (newIndex < 0) newIndex = tracks.length - 1;
  playTrack(newIndex);
}

function nextTrack() {
  if (tracks.length === 0) return;
  
  let newIndex = currentTrackIndex + 1;
  if (newIndex >= tracks.length) newIndex = 0;
  playTrack(newIndex);
}

function downloadAudio(url, name) {
  const fileName = `${name}.mp3`;
  
  if (chrome.downloads) {
    chrome.downloads.download({
      url: url,
      filename: fileName,
      saveAs: true
    }, (downloadId) => {
      if (chrome.runtime.lastError) fallbackDownload(url, fileName);
    });
  } else {
    fallbackDownload(url, fileName);
  }
}

function fallbackDownload(url, fileName) {
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

function updateProgress() {
  const { duration, currentTime } = audioPlayer;
  if (!duration) return;
  
  const progressPercent = (currentTime / duration) * 100;
  progress.style.width = `${progressPercent}%`;
  
  // 更新时间显示
  currentTimeEl.textContent = formatTime(currentTime);
  durationEl.textContent = formatTime(duration);
}

function formatTime(seconds) {
  const minutes = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${minutes}:${secs < 10 ? '0' : ''}${secs}`;
}

function setProgress(e) {
  if (!audioPlayer.duration) return;
  
  const width = this.clientWidth;
  const clickX = e.offsetX;
  const duration = audioPlayer.duration;
  audioPlayer.currentTime = (clickX / width) * duration;
}

function handleProgressDrag(e) {
  if (!isDragging) return;
  
  const rect = progressBar.getBoundingClientRect();
  const offsetX = e.clientX - rect.left;
  const percent = Math.min(Math.max(0, offsetX / rect.width), 1);
  
  progress.style.width = `${percent * 100}%`;
  currentTimeEl.textContent = formatTime(percent * audioPlayer.duration);
}

function handleProgressDragEnd(e) {
  if (!isDragging) return;
  isDragging = false;
  
  const rect = progressBar.getBoundingClientRect();
  const offsetX = e.clientX - rect.left;
  const percent = Math.min(Math.max(0, offsetX / rect.width), 1);
  audioPlayer.currentTime = percent * audioPlayer.duration;
}

function handleRefresh() {
  refreshBtn.disabled = true;
  refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 加载中...';
  
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, {action: "refreshAudio"}, (response) => {
      setTimeout(() => {
        refreshBtn.disabled = false;
        refreshBtn.innerHTML = '<i class="fas fa-sync-alt"></i> 刷新列表';
        loadAudioUrls();
      }, 1000);
    });
  });
}

// 初始化
loadAudioUrls();
const fun2 = ()=>{
    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
        if (chrome.runtime.lastError) {
            console.error(chrome.runtime.lastError);
            return;
        }

        chrome.tabs.sendMessage(tabs[0].id, {action: "onLoads"}, (response) => {
           if(response?.hasUrl ?? false){
                bat.className =  "music-player top"
                ezdax.className = "end" 
            }
            else{
                bat.className = "music-player end"
                ezdax.className = "top" 
            } 
        });
    });
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse)=>{
    if(request.name === 'onLoad'){
        bat.className =  "music-player top"
        ezdax.className = "end" 
        tracks = request.data;
    }
    return true; // 表明会异步响应
}); 
  

fun2({}); 
sub.addEventListener('click',function(){
    const val = Input.value;
    if(!val.includes('@汽水音乐 ')){
        alert('目前仅支持汽水音乐解析!')
        return;
    }
    const arr = val.split('@汽水音乐 ')
    const url = arr.pop();
    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
        chrome.tabs.sendMessage(tabs[0].id, {action: "ListGo",url:url});
    });
})
